package org.example.controller;

import io.swagger.annotations.*;
import org.example.model.Order;
import org.example.model.OrderStats;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "订单管理接口")
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private List<Order> orders = new ArrayList<>();

    @ApiOperation(value = "创建订单", notes = "创建一个新的订单")
    @ApiResponses({
        @ApiResponse(code = 200, message = "创建成功"),
        @ApiResponse(code = 400, message = "请求参数错误"),
        @ApiResponse(code = 404, message = "商品不存在")
    })
    @PostMapping
    public Order createOrder(@ApiParam(value = "订单信息", required = true) @RequestBody Order order) {
        order.setId(System.currentTimeMillis());
        order.setCreateTime(LocalDateTime.now());
        order.setStatus(Order.OrderStatus.PENDING);
        orders.add(order);
        return order;
    }

    @ApiOperation(value = "获取订单列表", notes = "获取所有订单信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", dataType = "Long"),
        @ApiImplicitParam(name = "status", value = "订单状态", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "string", format = "date-time"),
        @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "string", format = "date-time")
    })
    @GetMapping
    public List<Order> getOrders(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Order.OrderStatus status,
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime) {
        return orders.stream()
                .filter(o -> userId == null || o.getUserId().equals(userId))
                .filter(o -> status == null || o.getStatus() == status)
                .filter(o -> startTime == null || !o.getCreateTime().isBefore(startTime))
                .filter(o -> endTime == null || !o.getCreateTime().isAfter(endTime))
                .collect(Collectors.toList());
    }

    @ApiOperation(value = "获取订单详情", notes = "根据订单ID获取订单详细信息")
    @ApiImplicitParam(name = "id", value = "订单ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Long id) {
        return orders.stream()
                .filter(order -> order.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    @ApiOperation(value = "更新订单状态", notes = "更新指定订单的状态")
    @PatchMapping("/{id}/status")
    public Order updateOrderStatus(
            @ApiParam(value = "订单ID", required = true) @PathVariable Long id,
            @ApiParam(value = "订单状态", required = true) @RequestParam Order.OrderStatus status) {
        return orders.stream()
                .filter(o -> o.getId().equals(id))
                .findFirst()
                .map(o -> {
                    o.setStatus(status);
                    return o;
                })
                .orElse(null);
    }

    @ApiOperation(value = "取消订单", notes = "取消指定的订单")
    @PostMapping("/{id}/cancel")
    public Order cancelOrder(@ApiParam(value = "订单ID", required = true) @PathVariable Long id) {
        return orders.stream()
                .filter(o -> o.getId().equals(id))
                .filter(o -> o.getStatus() == Order.OrderStatus.PENDING)
                .findFirst()
                .map(o -> {
                    o.setStatus(Order.OrderStatus.CANCELLED);
                    return o;
                })
                .orElse(null);
    }

    @ApiOperation(value = "获取用户订单统计", notes = "获取指定用户的订单统计信息")
    @GetMapping("/stats/user/{userId}")
    public OrderStats getUserOrderStats(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        List<Order> userOrders = orders.stream()
                .filter(o -> o.getUserId().equals(userId))
                .collect(Collectors.toList());

        OrderStats stats = new OrderStats();
        stats.setTotalOrders((long) userOrders.size());
        stats.setPendingOrders(userOrders.stream().filter(o -> o.getStatus() == Order.OrderStatus.PENDING).count());
        stats.setCompletedOrders(userOrders.stream().filter(o -> o.getStatus() == Order.OrderStatus.COMPLETED).count());
        stats.setCancelledOrders(userOrders.stream().filter(o -> o.getStatus() == Order.OrderStatus.CANCELLED).count());
        stats.setTotalAmount(userOrders.stream()
                .map(Order::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        return stats;
    }
} 